package com.qc31.monitorlib.ui.video.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSeekBar
import com.qc31.comlib.TimeUtil
import com.qc31.monitorlib.R
import com.qc31.monitorlib.ui.video.CustomVideoManager
import com.qc31.monitorlib.ui.video.observer.TmnVideoListener
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.subjects.PublishSubject
import java.util.concurrent.TimeUnit

/**
 *@Author Jasper
 *@Time   2020/9/29
 *@Desc   todo
 */
class TmnVideo : StandardGSYVideoPlayer {
    //记住切换数据源类型
    private var mScaleType = 0

    //是否需要静音
    private var isNeedMute = true

    private var mProgress: Long = 0
    private var maxProgress: Long = 0
    private var maxStrTime: String = TimeUtil.zeroHms

    private var tmnVideoListener: TmnVideoListener? = null

    private lateinit var ivSwitchVoice: ImageView
    private lateinit var tvSwitchScale: TextView
    private lateinit var tvTmnTime: TextView
    private lateinit var tvTitle: TextView
    private lateinit var videoProgress: AppCompatSeekBar
    private lateinit var loadingProgress: ProgressBar

    lateinit var startPlay: ImageView
    lateinit var tvTmnMultiple: TextView
    lateinit var tvTmnPlayOperate: TextView
    lateinit var tvBack: ImageView

    val progressSub: PublishSubject<Long> by lazy {
        PublishSubject.create<Long>()
    }

    constructor(context: Context?, fullFlag: Boolean?) : super(context, fullFlag)
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun init(context: Context?) {
        super.init(context)
        ivSwitchVoice = findViewById(R.id.ivSwitchVoice)
        tvSwitchScale = findViewById(R.id.tvSwitchScale)
        tvTmnMultiple = findViewById(R.id.tvTmnMultiple)
        loadingProgress = findViewById(R.id.loadingProgress)
        tvBack = findViewById(R.id.tvBack)
        startPlay = findViewById(R.id.startPlay)
        tvTitle = findViewById(R.id.tvTitle)
        videoProgress = findViewById(R.id.videoProgress)
        tvTmnTime = findViewById(R.id.tvTmnTime)
        tvTmnPlayOperate = findViewById(R.id.tvTmnPlayOperate)


        setIsTouchWiget(false)//禁止滑动
        setIsTouchWigetFull(false)//禁止滑动改变声音
        isRotateViewAuto = true
        isLockLand = false
        isReleaseWhenLossAudio = false
        isNeedLockFull = false
        setThumbPlay(false)
        mDismissControlTime = 4000
        setListener()
        initSeekBar()

        ivSwitchVoice.isSelected = true
        CustomVideoManager.instance.isNeedMute = true
    }


    override fun getLayoutId(): Int {
        return R.layout.layout_tmn_video
    }

    override fun isTouchWiget(): Boolean {
        return false
    }

    private fun setListener() {
        //切换比例
        tvSwitchScale.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            when (mScaleType) {
                0 -> {
                    mScaleType = 1
                }
                1 -> {
                    mScaleType = 2
                }
                2 -> {
                    mScaleType = 3
                }
                3 -> {
                    mScaleType = 0
                }
            }
            resolveTypeUI()
        }

        //切换声音
        ivSwitchVoice.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            isNeedMute = !isNeedMute
            ivSwitchVoice.isSelected = isNeedMute
            CustomVideoManager.instance.isNeedMute = isNeedMute
        }

        //倍速切换
        tvTmnMultiple.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            tmnVideoListener?.onMultipleClickListener()
        }

        //播放状态操作
        tvTmnPlayOperate.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            tmnVideoListener?.onPlayOperateClickListener()
        }
    }

    override fun hideAllWidget() {
        super.hideAllWidget()
        mDismissState?.onDismiss()
    }


    /**
     * 是否展示加载
     */
    fun showProgress(isShow: Boolean) {
        if (isShow) {
            loadingProgress.visibility = View.VISIBLE
            startPlay.visibility = View.GONE
        } else {
            loadingProgress.visibility = View.GONE
        }
    }


    /**
     * 设置倍速
     */
    fun setMultipleTitle(title: String) {
        tvTmnMultiple.text = title
    }

    /**
     * 设置倍速是否显示
     */
    fun setMultipleVisibility(isShow: Boolean) {
        tvTmnMultiple.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    fun setVideoTitle(title: String) {
        tvTitle.text = title
    }

    private fun initSeekBar() {
        videoProgress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (!mHadPlay) {
                    return
                }
                mProgress = progress.toLong()
                tvTmnTime.text = "${TimeUtil.instance.formatLongTime(mProgress)}/$maxStrTime"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                stopTime()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                progressSub.onNext(mProgress)
                startTime()
            }
        })
    }

    /**
     * 设置seekbar状态
     */
    fun setSeekBarState(time: Long) {
        maxProgress = time
        maxStrTime = TimeUtil.instance.formatLongTime(time)
        videoProgress.max = time.toInt()
        videoProgress.progress = 0
        mProgress = 0
        tvTmnTime.text = "${TimeUtil.zeroHms}/$maxStrTime"
    }

    /**
     * 显示比例
     * 注意，GSYVideoType.setShowType是全局静态生效，除非重启APP。
     */
    private fun resolveTypeUI() {
        if (!mHadPlay) {
            return
        }
        when (mScaleType) {
            1 -> {
                tvSwitchScale.text = "16:9"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9)
            }
            2 -> {
                tvSwitchScale.text = "4:3"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3)
            }
            3 -> {
                tvSwitchScale.setText(R.string.desc_video_full_screen)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
            }
            0 -> {
                tvSwitchScale.setText(R.string.desc_video_default_ratio)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
            }
        }
        changeTextureViewShowType()
        if (mTextureView != null) mTextureView.requestLayout()
    }

    /**
     * 设置播放按钮图标
     */
    override fun updateStartImage() {
        when (mCurrentState) {
            GSYVideoView.CURRENT_STATE_PLAYING -> {
                startPlay.setImageResource(R.mipmap.video_pause_pressed)
            }
            GSYVideoView.CURRENT_STATE_ERROR -> {
                startPlay.setImageResource(R.mipmap.video_play_normal)
            }
            else -> {
                startPlay.setImageResource(R.mipmap.video_play_normal)
            }
        }
    }

    private var disposable: Disposable? = null
    fun startTime() {
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                mProgress += 1000
                videoProgress.progress = mProgress.toInt()
                tvTmnTime.text = "${TimeUtil.instance.formatLongTime(mProgress)}/$maxStrTime"
            }
    }

    fun stopTime() {
        if (disposable != null && disposable?.isDisposed == false) {
            disposable?.dispose()
            disposable = null
        }
    }

    override fun touchDoubleUp(e: MotionEvent?) {
        super.touchDoubleUp(e)
    }

    override fun touchSurfaceMove(deltaX: Float, deltaY: Float, y: Float) {}

    override fun getGSYVideoManager(): GSYVideoViewBridge {
        return CustomVideoManager.instance
    }

    override fun setStateAndUi(state: Int) {
        super.setStateAndUi(state)
        when (state) {
            GSYVideoView.CURRENT_STATE_PLAYING -> {
                startTime()
                startPlay.visibility = View.GONE
            }
            GSYVideoView.CURRENT_STATE_PAUSE,
            GSYVideoView.CURRENT_STATE_AUTO_COMPLETE,
            GSYVideoView.CURRENT_STATE_ERROR -> stopTime()
        }
    }

    /**
     * 设置倍速
     */
    fun setMultipleTitle(multipleId: Int) {
        tvTmnMultiple.setText(multipleId)
    }

    /**
     * 设置播放状态
     */
    fun setPlayState(stateId: Int) {
        tvTmnPlayOperate.setText(stateId)
    }

    /**
     * 控制界面消失监听
     */
    private var mDismissState: DismissState? = null
    fun setDismissState(dismissState: DismissState) {
        mDismissState = dismissState
    }

    interface DismissState {
        fun onDismiss()
    }

}